//声明构造函数
function Promise(executor) {
    //状态属性
    this.PromiseState = 'pending';
    //结果值
    this.PromiseResult = undefined;
    //声明属性 保存待执行的回调
    this.callbacks = [];// 可能会保存多组回调

    //声明 success
    let success = (value) => {
        //判断
        if(this.PromiseState !== 'pending') return;
        //修改状态
        this.PromiseState = 'fulfilled';
        //设置结果值
        this.PromiseResult = value;
        //执行 待执行的回调
        if(this.callbacks.length > 0){
            this.callbacks.forEach(cbObj => {
                //执行成功的回调
                cbObj.ok(this.PromiseResult);
            })
        }
    }

    //声明 fail
    let fail = (reason) => {
        //判断
        if(this.PromiseState !== 'pending') return;
        //修改状态
        this.PromiseState = 'rejected';
        //设置结果值
        this.PromiseResult = reason;
        //执行待执行的回调
        if(this.callbacks.length > 0){
            this.callbacks.forEach(cbObj => {
                //执行成功的回调
                cbObj.ng(this.PromiseResult);
            })
        }
    }

    try {
        //调用执行器函数
        executor(success, fail);
    } catch (e) {
        //修改状态和结果值
        fail(e);
    }
}


//原型声明 then 方法    on 当..时候      
Promise.prototype.then = function (onFulfilled, onRejected) {
    //执行回调
    //判断 promise 对象的状态
    if (this.PromiseState === 'fulfilled') {
        onFulfilled(this.PromiseResult);
    }

    if (this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult);
    }

    //针对 pending 做处理
    if(this.PromiseState === 'pending'){
        //  onFulfilled     onRejected
        //保存两个回调函数
        this.callbacks.push({
            ok: function(v){
                //promise 对象成功的回调
                onFulfilled(v);
            },
            ng: function(r){
                //promise 对象失败的回调
                onRejected(r);
            }
        })
    }
}